package com.jeremyfeinstein.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/*
 * AES对称加密和解密
 */
public class AESUtil {

    private static String AES_K = "";
    public static final String CODE_TYPE = "UTF-8";

    public static final String AES_TYPE = "AES/ECB/PKCS5Padding";

    public static String encrypt(String cleartext) {

        try {
            byte[] b = getAesK();
            SecretKeySpec key = new SecretKeySpec(b, "AES");
            b = null;
            Cipher cipher = Cipher.getInstance(AES_TYPE);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] encryptedData = cipher.doFinal(cleartext.getBytes(CODE_TYPE));
            return new BASE64Encoder().encode(encryptedData);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 解密
     *
     * @param encrypted
     * @return
     */
    public static String decrypt(String encrypted) {
        try {
            byte[] byteMi = new BASE64Decoder().decodeBuffer(encrypted);
            byte[] b = getAesK();
            SecretKeySpec key = new SecretKeySpec(b, "AES");
            b = null;
            Cipher cipher = Cipher.getInstance(AES_TYPE);
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] decryptedData = cipher.doFinal(byteMi);
            return new String(decryptedData, CODE_TYPE);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static byte[] getAesK() {
        byte[] a = null;
        try {
            a = RSAUtils.decryptByPrivateKey(ConferenceApp.getPriK(), AES_K);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return a;
    }

    public static void setAesK(String aesK) {
        AES_K = aesK;
    }
}